<?php
/**
 * @title 133. 克隆图 - 连通图和数组相互转换
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {
    /**
     * @param Node $node
     * @return Node
     */
    function cloneGraph($node) {
        /**
         * @since 2020-08-12 空图
         */
        if($node->val === null){
            return [];
        } else {}

        /**
         * @since 2020-08-12 哈希
         */
        $hashs = [];

        /**
         * @since 2020-08-12 连通图
         */
        $nodes = [$node];
        while($nodes){
            $nodesTmp = [];

            /**
             * @since 2020-08-12 遍历
             */
            foreach ($nodes as $node){
                $val = $node->val;

                /**
                 * @since 2020-08-12 防止重复
                 */
                if(!isset($hashs[$val])){
                    $nArray = [];
                    foreach($node->neighbors as $neighbor){
                        $nVal = $neighbor->val;
                        $nArray[] = $nVal;

                        /**
                         * @since 2020-08-12 下次循环的点
                         */
                        $nodesTmp[] = $neighbor;
                    }
                    $hashs[$val] = $nArray;
                } else {}
            }

            /**
             * @since 2020-08-12 下次循环
             */
            $nodes = $nodesTmp;
        }

        /**
         * @since 2020-08-12 长度
         */
        $len=count($hashs);

        /**
         * @since 2020-08-12 节点
         */
        $nodes = [];

        /**
         * @since 2020-08-12 遍历
         */
        for($i=1; $i<=$len; $i++){
            $nodes[$i] = new Node($i);
        }

        /**
         * @since 2020-08-12 邻接列表
         */
        for ($i=1; $i<=$len; $i++){
            $neighbors = [];
            foreach ($hashs[$i] as $key){
                $neighbors[] = $nodes[$key];
            }
            $nodes[$i]->neighbors = $neighbors;
        }

        /**
         * @return
         */
        return $nodes[1];
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.12.php
 */
$datas = [
    // [[2,4],[1,3],[2,4],[1,3]],
    [],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->cloneGraph($xhprof->Node($data));
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
